<template>
  <div class="login">
    <div class="from">
      <h1 class="title">叩丁狼商品管理系统</h1>
      <el-form :model="ruleForm" status-icon :rules="rules" ref="loginFrom">
        <el-form-item prop="username">
          <el-input
            prefix-icon="UserFilled"
            v-model="ruleForm.username"
            placeholder="请输入账号"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="ruleForm.password"
            prefix-icon="Lock"
            type="password"
            placeholder="请输入密码"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm()">登录 </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref } from "vue";
import * as http from "@/request";
import { useRouter } from "vue-router";
import Cookie from "js-cookie";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/store/modules/user";
const router = useRouter();
const loginFrom = ref();
const ruleForm = reactive({
  username: "",
  password: "",
});

const checkUser = (
  rule: unknown,
  value: string | undefined,
  cb: (msg?: string) => void
) => {
  if (!value) {
    cb("用户名不能为空");
  } else {
    cb();
  }
};
const checkPassword = (
  rule: unknown,
  value: string | undefined,
  cb: (msg?: string) => void
) => {
  if (!value) {
    cb("密码不能为空");
  } else {
    cb();
  }
};
const rules = reactive({
  username: [{ validator: checkUser, trigger: "blur" }],
  password: [{ validator: checkPassword, trigger: "blur" }],
});

const submitForm = async () => {
  try {
    await loginFrom.value.validate();
    let res = await http.adminLogin({
      username: ruleForm.username,
      password: ruleForm.password,
    });
    if (res.code === 200) {
      Cookie.set("token", res.data.tokenHead + res.data.token);
      ElMessage({
        message: "登录成功",
        type: "success",
      });
      router.push("/home");
    } else {
      ElMessage({
        message: res.message,
        type: "error",
      });
    }
  } catch (error) {
    console.log("验证失败");
  }
};
</script>
<style lang="scss" scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100vw;
  height: 100vh;
  background-color: #2d3a4b;
  .title {
    width: 100%;
    padding: 15px 0;
    font-size: 24px;
    text-align: center;
    color: #fff;
    font-weight: 700;
  }
  .from {
    width: 420px;
    :deep(.el-button) {
      width: 100%;
    }
    :deep(.el-input__wrapper) {
      background-color: rgba(0, 0, 0, 0.1);
      height: 50px;
    }
    :deep(.el-input__inner) {
      color: #fff;
    }
    :deep(.el-button) {
      height: 40px;
    }
  }
}
</style>
